package com.wxb.controller;

import com.alibaba.fastjson.JSONObject;
import com.wxb.common.core.web.domain.AjaxResult;
import com.wxb.common.redis.service.RedisService;
import com.wxb.common.security.utils.SecurityUtils;
import com.wxb.common.util.J2CacheUtils;
import com.wxb.domain.MallBuyGoodsEntity;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @Date 2025-05-30 17:03
 * @Version 1.0
 * @Description
 * @ClassName MallBuyController
 **/
@RestController
@RequestMapping("/buy")
public class MallBuyController {
    /**
     * 得到request对象
     */
    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private RedisService redisService;

    @ApiOperation(value = "商品添加")
    @PostMapping("/add")
    public Object addBuy() {
        JSONObject jsonParam = getJsonRequest();
        Integer goodsId = jsonParam.getInteger("goodsId");
        Integer productId = jsonParam.getInteger("productId");
        Integer number = jsonParam.getInteger("number");
        MallBuyGoodsEntity goodsVo = new MallBuyGoodsEntity();
        goodsVo.setGoodsId(goodsId);
        goodsVo.setProductId(productId);
        goodsVo.setNumber(number);
        redisService.setCacheMapValue("shopCache", "goods" + SecurityUtils.getUserId() + "" ,goodsVo);
        return AjaxResult.success("添加成功");
    }
    public JSONObject getJsonRequest() {
        JSONObject result = null;
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader();) {
            char[] buff = new char[1024];
            int len;
            while ((len = reader.read(buff)) != -1) {
                sb.append(buff, 0, len);
            }
            result = JSONObject.parseObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
